import esbuild from 'esbuild'
import child_process from 'child_process'
import electron from 'electron'

const devPlugin = () => {
  return {
    name: 'dev-plugin',
    configureServer(server: any) {
      esbuild.buildSync({
        entryPoints: ['./electron/main.js'],
        bundle: true,
        platform: 'node',
        outfile:'./dist/main.cjs',
        external: ['electron']
      })
      server.httpServer.once('listening', () => {
        const { spawn } = child_process
        const electronProcess = spawn(
          electron.toString(),
          ['./dist/main.cjs', `http://localhost:${server.httpServer.address().port}` ],
          {
            cwd: process.cwd(),
            stdio: 'inherit'
          }
        )
        electronProcess.on('close', () => {
          server.close()
          process.exit()
        })
      })
    }
  }
}

module.exports = {
  devPlugin: devPlugin
}
